import { Canvas, View } from '@tarojs/components'
import React, { useEffect, useRef } from 'react'
import { registerCanvas } from '@galacean/appx-adapter/weapp'
import { Player } from '@galacean/effects/weapp'
import Taro from '@tarojs/taro'

export default function Home() {
  const initGalacen = async () => {
    const query = Taro.createSelectorQuery()
    query
      .select('#canvasRef')
      .fields({ node: true, size: true })
      .exec(async res => {
        if (res[0]) {
          const canvas = await registerCanvas({ id: res[0].node })

          const player = new Player({
            transparentBackground: true,
            canvas: canvas,
            pixelRatio: 1,
            renderFramework: 'webgl',
            interactive: true,
            onError: (err: any) => {
              console.error('player error', err)
            },
          })

          const scene = await player.loadScene([
            {
              url: 'https://cdn.wxhand.com/test-file/%E7%BA%A2%E5%8C%85%E9%9B%A8(1)/%E7%BA%A2%E5%8C%85%E9%9B%A8.json',
            },
            {
              url: 'https://gw.alipayobjects.com/os/gltf-asset/mars-cli/GPWMSPWHOIOO/-545104665-90021.json',
              options: { autoplay: false, reusable: false },
            },
          ])

          console.log('scene', scene[0]?.play(), player)

          player.on('click', item => {
            console.log(item, scene[1])

            scene[1]?.reset?.()
            scene[1]?.gotoAndStop(0)
            scene[1]?.gotoAndPlay(0)
            console.log('------', item.hitPositions[0])
            scene[1]?.setPosition(
              item.hitPositions[0].x,
              item.hitPositions[0].y,
              item.hitPositions[0].z,
            )
            scene[1]?.setScale(0.2, 0.2, 0.2)
          })

          player.on('message', (item: any) => {
            console.log(item.name) // 设置多个交互元素需要根据 name 判断是否指定元素
          })
        } else {
          console.error('canvasRef not found')
        }
      })
  }

  useEffect(() => {
    initGalacen()
  }, [])
  return (
    <React.Fragment>
      <View
        style={{
          width: '100vw',
          height: '100vh',
          background: '#000',
        }}
      >
        <Canvas
          id="canvasRef"
          type="webgl"
          canvasId="canvasRef"
          style={{ width: '100%', height: '100%' }}
        ></Canvas>
      </View>
    </React.Fragment>
  )
}
